package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInContractDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.IRoomService;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.util.IDCardUtils;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 *
 * @author ruoyi
 * @date 2025-06-09
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }


    /**
     * 查询入住详情
     * @param id)
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        //通过id找到入住配置 获取老人id
        CheckIn checkIn = checkInMapper.selectCheckInById(id);
        //通过老人id查询老人信息
        Elder elder = elderMapper.selectElderById(checkIn.getElderId());
        if (ObjectUtil.isNotEmpty(elder)) {
            //数据拷贝
            CheckInElderVo checkInElderVo = new CheckInElderVo();
            BeanUtils.copyProperties(elder,checkInElderVo);

            //补全年龄属性,通过身份证号来计算老人的年龄，工具类可以使用AI协助创建
            checkInElderVo.setAge(IDCardUtils.getAgeByIdCard(elder.getIdCardNo()));
            checkInElderVo.setBirthday(IDCardUtils.getBirthDateByIdCard(elder.getIdCardNo()).toString());
            //将信息存入所需要的数据体中
            checkInDetailVo.setCheckInElderVo(checkInElderVo);

        }

        //入住配置信息
        LambdaQueryWrapper<CheckInConfig> checkInConfigWrapper = new LambdaQueryWrapper<>();
        checkInConfigWrapper.eq(CheckInConfig::getCheckInId,checkIn.getId());
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(checkInConfigWrapper);
        //属性拷贝，BeanUtil.toBean:拷贝数据并创建对象(糊涂工具提供)
        CheckInConfigVo checkInConfigVo = BeanUtil.toBean(checkInConfig, CheckInConfigVo.class);
        //全入住开始时间和结束时间
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());

        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);

        //合同
        LambdaQueryWrapper<Contract> contractWrapper = new LambdaQueryWrapper<>();
        contractWrapper.eq(Contract::getElderId,elder.getId());
        Contract contract = contractMapper.selectOne(contractWrapper);
        checkInDetailVo.setContract(contract);

        //家属列表
        String otherApplyInfo = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilyList = JSON.parseArray(otherApplyInfo, ElderFamilyVo.class);
        checkInDetailVo.setElderFamilyVoList(elderFamilyList);
        return checkInDetailVo;
    }

    /**
     * 申请入住
     *
     * @param checkInApplyDto
     */
    @Transactional
    @Override
    public void apply(CheckInApplyDto checkInApplyDto) {
        try {
            //判断老人是否入住，假如老人已经入住，提示:老人已入住 结束程序
            LambdaQueryWrapper<Elder> elderLambdaQueryWrapper = new LambdaQueryWrapper<>();
            //根据身份证号查查询
            elderLambdaQueryWrapper.eq(Elder::getIdCardNo, checkInApplyDto.getCheckInElderDto().getIdCardNo());
            elderLambdaQueryWrapper.eq(Elder::getStatus, 1);
            Elder elder = elderMapper.selectOne(elderLambdaQueryWrapper);
            if (ObjectUtil.isNotEmpty(elder)) {
                throw new RuntimeException("老人已入住");
            }

            //更新老人选择的床位状态
            Bed bed = bedMapper.selectBedById(checkInApplyDto.getCheckInConfigDto().getBedId());
            bed.setBedStatus(1);
            bedMapper.updateById(bed);
            //更新或新增老人
            elder = inserOrUpdateElder(bed, checkInApplyDto.getCheckInElderDto());

            //新增签约办理信息合同
            //生成一个铬铜编号
            String contractNo = "HT"+CodeGenerator.generateContractNumber();
            insertContract(elder,contractNo,checkInApplyDto);
            //新增入住信息
            CheckIn checkIn = inserCheckIn(elder, bed, checkInApplyDto);

            //新增入住配置信息
            insertCheckInConfig(checkIn.getId(),checkInApplyDto);
        } catch (RuntimeException e) {
            throw new BaseException("入住失败");
        }

    }
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    /**
     * 新增入住配置
     * @param checkInApplyDto
     */
    private void insertCheckInConfig(Long checkInId, CheckInApplyDto checkInApplyDto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(),checkInConfig);
        checkInConfig.setCheckInId(checkInId);
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     *  新增入住信息
     * @param elder
     * @param bed
     * @param checkInApplyDto
     */
    private CheckIn inserCheckIn(Elder elder, Bed bed, CheckInApplyDto checkInApplyDto) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setNursingLevelName(checkInApplyDto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setStatus(0);
        //家属列表，，转换为json存在remark字段3
        checkIn.setRemark(JSON.toJSONString(checkInApplyDto.getElderFamilyDtoList()));
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    @Autowired
    private ContractMapper contractMapper;
    /**
     * 保存合同数据
     * @param elder
     * @param contractNo
     * @param checkInApplyDto
     */
    private void insertContract(Elder elder, String contractNo, CheckInApplyDto checkInApplyDto) {
        //属性拷贝
        CheckInContractDto checkInContractDto = checkInApplyDto.getCheckInContractDto();
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInContractDto, contract);
        //老人相关的，合同编号、状态，时间
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        contract.setContractNumber(contractNo);
        LocalDateTime startDate = checkInApplyDto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = checkInApplyDto.getCheckInConfigDto().getEndDate();
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        //设置状态
        Integer status = startDate.isAfter(LocalDateTime.now()) ? 1 : 0;
        contract.setStatus(status);
        contractMapper.insert(contract);
    }

    /**
     * 新增或更新老人
     *
     * @param bed
     * @param checkInElderDto
     */
    private Elder inserOrUpdateElder(Bed bed, CheckInElderDto checkInElderDto) {
        //属性拷贝
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInElderDto, elder);
        elder.setBedNumber(bed.getBedNumber());
        elder.setBedId(bed.getId());
        elder.setStatus(1);

        LambdaQueryWrapper<Elder> elderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //根据身份证号查查询
        elderLambdaQueryWrapper.eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo());
        elderLambdaQueryWrapper.eq(Elder::getStatus, 0);
        Elder elderDb = elderMapper.selectOne(elderLambdaQueryWrapper);
        if (ObjectUtil.isNotEmpty(elderDb)) {
            //更新
            elder.setId(elderDb.getId());
            //更新
            elderMapper.updateById(elder);
        } else {
            //新增
            elderMapper.insert(elder);
        }
        return elder;
    }
}